package com.alibaba.org.controller;

import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.PageList;
import com.alibaba.org.domain.Employee;
import com.alibaba.org.query.EmployeeQuery;
import com.alibaba.org.service.IEmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 接口类：部门
 */
@RestController
@RequestMapping("/employee")

public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 查询一个
     * @param id
     * @return
     */
    @GetMapping("/{id}") // http://localhost:8080/employee/1 + get
    public Employee findOne(@PathVariable Long id){
       return employeeService.findById(id);
    }

    /**
     * 查询所有
     * @return
     */

    @GetMapping // http://localhost:8080/employee + get  与上面的请求参数不同所以请求方式是不一样的
    public List<Employee> findAll(){

        return employeeService.findAll();
    }

    /**
     * 删除操作
     * @param id
     * @return
     */

    @DeleteMapping("/{id}") // http://localhost:8080/employee + delete
    public AjaxResult del(@PathVariable Long id){
        try {
            employeeService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    /**
     * 添加或修改
     * @param employee
     * @return
     */

    @PutMapping // http://localhost:8080/employee +JSon对象 + delete
    public AjaxResult addOrUpdate(@RequestBody Employee employee){ // 从请求体中获取JSON对象

        try {
            if (employee.getId() == null){
                employeeService.add(employee);

            } else {
                employeeService.update(employee);
            }
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }

    /**
     * 分页查询
     * @param query
     * @return
     */

    @PostMapping// http://localhost:8080/employee +JSon对象 + post
    public PageList<Employee> queryPage(@RequestBody EmployeeQuery query){
            return employeeService.queryPage(query);
    }

    /**
     * 批量删除
     * @param
     * @return
     */

    @PatchMapping
    // 可以用数组 也可以用集合List<Long>
    public AjaxResult patchDel(@RequestBody Long[] ids){
        try {
            employeeService.patchDelete(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
}
